<?php

namespace App\Exceptions;

use Exception;
use App\Traits\Response\InterfaceResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * 异常处理
 *
 * Date: 21/03/2018
 * @author George
 * @package App\Exceptions
 */
class Handler extends ExceptionHandler
{
    use InterfaceResponse;

    /**
     * 定义不需要记录的异常类
     *
     * @var array
     */
    protected $dontReport = [
        HttpException::class,
        ValidationException::class,
        ModelNotFoundException::class,
        AuthorizationException::class,
        AuthenticationException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * 定义需要记录的异常
     *
     * Date: 21/03/2018
     * @author George
     * @param Exception $exception
     * @return mixed|void
     * @throws Exception
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * 拦截异常并生成对应的响应内容
     *
     * Date: 21/03/2018
     * @author George
     * @param \Illuminate\Http\Request $request
     * @param Exception $exception
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function render($request, Exception $exception)
    {
        // 拦截数据库操作异常
        if ($exception instanceof QueryException) {
            Log::error($exception);
            return $this->internalError();
        }

        // 拦截一般异常并生成响应
        if ($exception instanceof GeneralException) {
            return $this->failed($exception->getMessage(), $exception->getCode() ?: 500);
        }

        // 拦截404异常
        if ($exception instanceof ModelNotFoundException) {
            return $this->notFound();
        }

        // 拦截授权异常
        if ($exception instanceof AuthorizationException) {
            return $this->failed('您无权访问', 403);
        }

        // 参数验证错误的异常，我们需要返回 400 的 http code 和一句错误信息
        if ($exception instanceof ValidationException) {
            return $this->failed(array_first(array_collapse($exception->errors())), 422);
        }

        // 用户认证的异常，我们需要返回 401 的 http code 和错误信息
        if ($exception instanceof UnauthorizedHttpException) {
            return $this->failed('未提供Token', 401);
        }

        // 捕获404异常
        if ($exception instanceof NotFoundHttpException) {
            return $this->notFound();
        }

        return parent::render($request, $exception);
    }

    /**
     * 认证失败后抛出异常
     *
     * Date: 2018/5/27
     * @author George
     * @param \Illuminate\Http\Request $request
     * @param AuthenticationException $exception
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function unauthenticated($request, AuthenticationException $exception)
    {
        return $this->failed('身份认证失败', 401);
    }
}
